package com.desk.api.controller;

import com.desk.api.constant.LearnStatus;
import com.desk.api.emtity.Learn;
import com.desk.api.emtity.Result;
import com.desk.api.service.LearnService;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/desk/learn")
public class LearnController {

  @Resource LearnService learnService;

  @Schema(description = "获取学习状态")
  @GetMapping("/getLearnStatus")
  public Result<Map> getLearnStatus() {
    HashMap<String, Object> map = new HashMap<>();
    Learn lastStatus = learnService.lambdaQuery().orderByAsc(Learn::getTime).one();
    Learn lastStart =
        learnService
            .lambdaQuery()
            .eq(Learn::getStatus, LearnStatus.LEARN_START)
            .orderByAsc(Learn::getTime)
            .one();
    if (lastStatus == null) {
      return Result.success();
    }
    if (lastStatus.getStatus().equals(LearnStatus.LEARNED)) {
      return Result.success();
    }
    if (lastStart != null) {
      // 开始的时间
      map.put("startTime", lastStart.getTime());
      // 计算下次休息时间
      map.put(
          "nextWaitTime",
          System.currentTimeMillis()
              - lastStart.getTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
                  * 1000);
      // 计算当前已学习时间 单位分钟
      map.put(
          "learnTime",
          (System.currentTimeMillis()
                  - lastStart.getTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
                      * 1000)
              / 1000
              / 60);
      // 当前状态
      map.put("status", lastStatus.getStatus());
    }
    return Result.success(map);
  }
}
